package com.sping_boot3.spirng_boot3.juc;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;
import java.util.concurrent.RecursiveTask;

@Data
public class TiaolishiResult extends RecursiveTask<Map<String, Tiaolishi>> {
    //拆分差值不能超过10，计算10以内运算
    private static final Integer VALUE = 10;
    //需要查询的用户id
    List<Integer> userId = new ArrayList<>();
    //查询的结果
    Map<String, Tiaolishi> map = new HashMap<>();
    //拆分的开始值
    private Integer start;
    //拆分的结束值
    private Integer end;

    @Override
    protected Map<String, Tiaolishi> compute() {
        System.out.println(Thread.currentThread().getName()+"线程---");
        if (end - start <= VALUE) {
            ArrayList<Integer> arrayList = new ArrayList<>();
            //相加计算结果
            for (int i = start; i <= end; i++) {
                arrayList.add(i);
            }
            //从数据库查询
            System.out.println("查询中....");
            for (int i = 0; i < arrayList.size(); i++) {
                map.put(UUID.randomUUID().toString(),new Tiaolishi(new Random(100).nextInt(),new Random(20).nextInt(),new Random(100).nextInt()));
            }
        }else{
        //拆分
            Integer mid = (start + end) / 2;
            TiaolishiResult left = new TiaolishiResult(start, mid);
            TiaolishiResult right = new TiaolishiResult(mid + 1, end);
            left.fork();
            right.fork();
            map.putAll(left.join());
            map.putAll(right.join());;
            System.out.println("one:"+left.join() + "two:"+right.join());


        }
        return map;
    }

    public TiaolishiResult(Integer start, Integer end) {
        this.start = start;
        this.end = end;
    }

    public TiaolishiResult() {
    }

    public void setUserId(ArrayList<Integer> list){
        this.userId = list;
    }
}
